<template>
  <ElContainer class="bg-white">
    <el-main>
      <headersteps v-bind="{ active, successstatus, next, ruleForm }"></headersteps>
      <el-form :model="ruleForm" :rules="questionrules" ref="rule" label-width="150px" class="demo-ruleForm"
        :style="{ paddingTop: '24px' }">
        <el-tabs v-model="active" class="tabs" tab-position="left">
          <el-tab-pane label="0">
            <questionindexVue v-model:rule-form="ruleForm" v-model:checkbox="checkbox"
              v-bind="{ grouplabel, changeruleform, }">
              <template v-if="istype" #type>
                <el-form-item label="题目类型:" prop="type">
                  <QuestionButton class="m-mr-6"
                    v-bind="{ type: ruleForm.type === '代码', name: '代码', click: () => ruleForm.type = '代码' }">
                    <svg class="icon icon-class-var" aria-hidden="true">
                      <use
                        :xlink:href="ruleForm.type != '代码' ? '#icon-icon_tianjiatimu_code' : '#icon-icon_tianjiatimu_code-copy'" />
                    </svg>
                  </QuestionButton>
                  <QuestionButton class="m-mr-6"
                    v-bind="{ type: ruleForm.type === '单选', name: '单选', click: () => ruleForm.type = '单选' }">
                    <svg class="icon" aria-hidden="true">
                      <use
                        :xlink:href="ruleForm.type != '单选' ? '#icon-icon_tianjiatimu_single' : '#icon-icon_tianjiatimu_single-copy'" />
                    </svg>
                  </QuestionButton>
                  <QuestionButton class="m-mr-6"
                    v-bind="{ type: ruleForm.type === '多选', name: '多选', click: () => ruleForm.type = '多选' }">
                    <svg class="icon" aria-hidden="true">
                      <use
                        :xlink:href="ruleForm.type != '多选' ? '#icon-icon_tianjiatimu_multiple' : '#icon-icon_tianjiatimu_multiple-copy'" />
                    </svg>
                  </QuestionButton>
                  <QuestionButton class="m-mr-6"
                    v-bind="{ type: ruleForm.type === '判断', name: '判断', click: () => ruleForm.type = '判断' }">
                    <svg class="icon" aria-hidden="true">
                      <use
                        :xlink:href="ruleForm.type != '判断' ? '#icon-icon_tianjiatimu_panduan' : '#icon-icon_tianjiatimu_panduan-copy'" />
                    </svg>
                  </QuestionButton>

                  <QuestionButton class="m-mr-6"
                    v-bind="{ type: ruleForm.type === '填空', name: '填空', click: () => ruleForm.type = '填空' }">
                    <svg class="icon" aria-hidden="true">
                      <use
                        :xlink:href="ruleForm.type != '填空' ? '#icon-icon_tianjiatimu_edit' : '#icon-icon_tianjiatimu_edit-copy'" />
                    </svg>
                  </QuestionButton>
                  <QuestionButton class="m-mr-6"
                    v-bind="{ type: ruleForm.type === '排序', name: '排序', click: () => ruleForm.type = '排序' }">
                    <el-icon>
                      <Operation />
                    </el-icon>
                  </QuestionButton>
                </el-form-item>
              </template>
              <template v-if="isrange" #range>
                <RangeView v-model:rule-form="ruleForm"
                  v-bind="{ userhandleCurrentChange, userhandleCurrentChangeuser, }" />
              </template>
              <template v-if="isAdmin === 1" #version>
                <el-form-item label="题目版本:" prop="ismatch">
                  <el-input placeholder="请输入题目版本" v-model="ruleForm.version"></el-input>
                </el-form-item>
              </template>
              <template v-if="isAdmin === 1" #source>
                <el-form-item label="题目来源:" prop="source">
                  <!-- 单选框 CF 哈工科教 其他 -->
                  <el-radio-group v-model="ruleForm.source" size="default">
                    <el-radio-button label="CODEFORCES" value="CODEFORCES">CF</el-radio-button>
                    <el-radio-button label="哈工科教" value="哈工科教">哈工科教</el-radio-button>
                    <!-- <el-radio-button label="zhengrui" value="zhengrui">zhengrui</el-radio-button> -->
                    <!-- <el-radio-button label="其他" value="其他">其他</el-radio-button> -->
                    <el-input placeholder="请输入题目来源（外部显示）" v-model="ruleForm.source"></el-input>
                  </el-radio-group>
                </el-form-item>
                <el-form-item v-if="istype" v-show="ruleForm.type == '代码'" label="来源(oj网站):">
                  <el-input v-model="ruleForm.dataform"></el-input>
                </el-form-item>
              </template>
            </questionindexVue>
            <div class="row">
              <div class="col text-right">
                <el-button class="translateX-50" @click="next(1)"
                  :style="{ '--el-button-bg-color': '#434343', '--el-button-border-color': '#434343' }" size="large"
                  type="primary">
                  下一步，内容设置</el-button>
              </div>
              <div class="col text-right">
                <el-button type="info" size="large" @click="close">取消</el-button>
                <el-button @click="submit" type="primary" size="large">保存</el-button>
              </div>
            </div>
          </el-tab-pane>
          <el-tab-pane label="1">
            <CountextQuestionview ref="contexteditor" v-model:rule-form="ruleForm" v-model:checkbox="checkbox"
              v-bind="{ grouplabel, selectsA, selectchange, context, htmlcontext, istype, errormessage }">
              <template v-if="isrange" #range>
                <RangeView v-model:rule-form="ruleForm"
                  v-bind="{ userhandleCurrentChange, userhandleCurrentChangeuser, }" />
              </template>
              <template v-else #range>
                <el-form-item label="题目范围:" prop="range">
                  <el-radio-group v-model="ruleForm.range">
                    <el-radio label="team">团队可见</el-radio>
                    <el-radio label="user">仅自己可见</el-radio>
                  </el-radio-group>
                </el-form-item>
                <el-form-item v-if="ruleForm.range === 'team'" label="选择团队:">
                  <el-select v-model="ruleForm.teamid" placeholder="选择团队">
                    <el-option :label="v.name" :value="v.ID" v-for="v in teams" :key="v.ID"></el-option>
                  </el-select>
                </el-form-item>
              </template>
            </CountextQuestionview>
            <div class="row">
              <div class="col text-right">
                <el-button class="translateX-50" @click="next(2)" v-show="ruleForm.type === '代码'" size="large"
                  :style="{ '--el-button-bg-color': '#434343', '--el-button-border-color': '#434343' }" type="primary">
                  下一步，配置测试点</el-button>
              </div>
              <div class="col text-right">
                <el-button type="info" size="large" @click="close">取消</el-button>
                <el-button @click="submit" type="primary" size="large">保存</el-button>
              </div>
            </div>
          </el-tab-pane>
          <el-tab-pane :disabled="disabled" label="2">
            <Testcaseview @update:rule-form="changeruleform"
              v-bind="{ disabled, download, addexample, getname, request, downloadtip, settestcasesscore, ruleForm }" />
            <div class="row">
              <div class="col text-right">
                <el-button class="translateX-50" text-right translateX-50 v-show="ruleForm.isspecialjudge"
                  @click="next(3)" :style="{ '--el-button-bg-color': '#434343', '--el-button-border-color': '#434343' }"
                  size="large" type="primary">
                  下一步，SPJ设置</el-button>
              </div>
              <div class="col text-right">
                <el-button type="info" size="large" @click="close">取消</el-button>
                <el-button @click="submit" size="large" type="primary">保存</el-button>
              </div>
            </div>
          </el-tab-pane>
          <el-tab-pane :disabled="disabled" label="3">
            <Specialjudge v-model:rule-form="ruleForm" :ID="ruleForm.specialjudgeid" :change="spjchange"
              :show="active === '3'" ref="Specialjudgecontext" />
            <div class="row">
              <div class="col"></div>
              <div class="col text-right">
                <el-button type="info" size="large" @click="close">取消</el-button>
                <el-button @click="Specialjudgecontext?.submit" size="large" type="primary">保存</el-button>
              </div>
            </div>
          </el-tab-pane>
          <el-tab-pane :disabled="disabled" label="4" class="text-center">
            <el-button size="large" @click="() => start(true)" type="primary" class="icon-button">创建新的题目</el-button>
            <el-button size="large" type="info" class="icon-button">
              <router-link v-if="ID" :to="{ name: '题目', params: { ID: ID ? ID : 0 }, }" target="_bank">
                查看题目
              </router-link>
            </el-button>

            <el-button size="large" @click="close" class="icon-button">返回列表</el-button>
          </el-tab-pane>
        </el-tabs>
      </el-form>
    </el-main>
  </ElContainer>
</template>
<script setup lang="ts">
import { Operation } from '@element-plus/icons-vue';
import { ElMessage, ElMessageBox, ElNotification, UploadRequestHandler } from "element-plus";
import JSZip from "jszip";
import { assign } from "underscore";
import {
  computed,
  onMounted,
  onUnmounted,
  reactive,
  ref,
  toRaw,
  watch
} from "vue";
import { onBeforeRouteLeave, useRouter } from "vue-router";
import { useStore } from "vuex";
import { EMstatus, MyElForm, Storekey } from "../../../interface";
import Studycodemodel from "../../../mysql_interface/studycodemodel";
import { findpid } from "../../../util/code";
import { dealy } from "../../../util/time";
import { downloadexamplezip, updatezip } from "../../../util/updateoss";
import { Question } from "../../data";
import { questionrules } from "../../data/formrules";
import RangeView from "./adminrange.vue";
import CountextQuestionview from "./contextquestion.vue";
import headersteps from './headersteps.vue';
import QuestionButton from "./questionbutton.vue";
import questionindexVue from "./questionindex.vue";
import Specialjudge from "./specialjudge.vue";
import Testcaseview from "./testcase.vue";
type P = {
  close: () => void,
  getstart: (data: { ID: number }) => Promise<Studycodemodel.Iquestion>
  ID?: number | string,
  asynccreateorupdatequestion: (data: Studycodemodel.Iquestion) => Promise<Studycodemodel.Iquestion>,
  istype: boolean,
  isrange: boolean,
  teams: Studycodemodel.Iteam[],
  userid?: number,
  isAdmin?: boolean | 1 | 2
}
const router = useRouter()
const prop = defineProps<P>()

type Isuccessstatus = [EMstatus, EMstatus, EMstatus, EMstatus, EMstatus]

/**
 * 步骤条状态
 */
const successstatus = ref<Isuccessstatus>(['finish', 'wait', 'wait', 'wait', 'wait'])

/**
 * 当前第几页
 */
const active = ref('0')

/**
 * 用户团队选择
 */
const dialogVisible2 = ref(false);


/**
 * 初始化文本编辑器内容
 */
const context = ref("");

/**
 * 初始化文本编辑器内容2
 */
const htmlcontext = ref("");

/**
 * 错误提示
 */
const errormessage = ref("")

const Specialjudgecontext = ref()

/**
 * 答题主体组件
 */
const contexteditor = ref<typeof CountextQuestionview>();
const store = useStore(Storekey);
const isdon = ref(false);
const ruleForm = reactive<Studycodemodel.Iquestion>(assign({}, Question, { userid: prop.userid }));

function changeruleform(r: Studycodemodel.Iquestion) {
  Object.assign(ruleForm, r)
}

// formref
const rule = ref<MyElForm>();

questionrules.answer = [
  {
    required: true,
    trigger: "blur",
    validator(v, c) {
      console.log(c)
      if (ruleForm.type !== "代码") {
        if (v && ruleForm.answer !== null) {
          c();
        } else {
          c(new Error("请填写正确答案"));
        }
      } else {
        c();
      }
    },
  },
];

/**
 * 跳转
 */
async function next(num: 0 | 1 | 2 | 3 | 4) {
  if (num === 0) {
    active.value = String(num)
    successstatus.value = ['finish', 'wait', 'wait', 'wait', 'wait']
  } else if (num === 1) {
    if (ruleForm.type === '排序') {
      if (!ruleForm.answer) {
        ElMessage.error('排序题没有内容')
        return
      }
      ruleForm.answer.answer = Object.keys(ruleForm.answer.options.join(''))
    }
    rule.value?.validateField(['name'], (a, b) => {
      if (a) {
        active.value = String(num)
        successstatus.value = ['success', 'finish', 'wait', 'wait', 'wait']
      }
    })
  } else if (num === 2) {
    ruleForm.context = contexteditor.value?.gethtml()
    ruleForm.htmlcontext = contexteditor.value?.getcontext()
    ruleForm.errormessage = contexteditor.value?.geterrormessage()
    ruleForm.htmlerrormessage = contexteditor.value?.gethtmlerrormessage()

    rule.value?.validateField(['context'], (a, b) => {
      if (a) {
        active.value = String(num)
        successstatus.value = ['success', 'success', 'finish', 'wait', 'wait']
      }
    })
    // ruleForm.context = contexteditor.value?.gethtml()
    // ruleForm.htmlcontext = contexteditor.value?.getcontext()
    // rule.value?.validate((isValid, invalidFields) => {
    //   if (!isValid && invalidFields && rule.value) {
    //     validate(rule.value, invalidFields)
    //   } else {
    //     active.value = String(num)
    //     successstatus.value = ['success', 'finish', 'wait', 'wait', 'wait']
    //   }
    // })

  } else if (num === 3) {
    active.value = String(num)
    successstatus.value = ['success', 'success', 'success', 'finish', 'wait']
  }
}

/**
 * spj 修改
 * @param ID 
 */
function spjchange(ID: number) {
  ruleForm.specialjudgeid = ID
  submit()
}

const grouplabel = computed(() => {
  const data = store.state.label?.rows.filter((e) => e.type === "题目标签");
  return findpid(data ? data : []);
});

const selectsA = computed(() => {
  const answer = ruleForm.answer;
  if (answer && Array.isArray(answer.options)) {
    return answer.options;
  }
  return ["", "", "", ""];
});

onMounted(async () => {
  window.onbeforeunload = function (e) {
    if (t.value) {
      return window.confirm('确定退出')
    }
    return true
  }
  // 初始化
  await start();
  // 是否有团队

});

const disabled = computed(() => {
  return ruleForm.type !== "代码";
});

/**
 * // 答案修改
 */
function selectchange(t: string, m: string, k: number) {
  if (ruleForm.answer && ruleForm.answer.options) {
    if (!Array.isArray(ruleForm.answer.options)) {
      ruleForm.answer.options = ["", "", "", ""];
    } else if (ruleForm.answer.options.length != 4) {
      ruleForm.answer.options = ["", "", "", ""];
    }
    ruleForm.answer.options.splice(k, 1, m ? m : t);
  }
}
/**
 * 标记是否修改过
 */
const t = ref(false)
watch(ruleForm, async (v, o) => {
  isdon.value = true;
  if (v.type !== o.type) {
    v.answer = {
      answer: "",
      options: [],
    };
  }
  t.value = true
});

watch(
  () => prop.ID,
  async () => {
    await start();
  }
);

async function download() {
  const example = ruleForm.testcases
  if (example && example.length) {
    ElMessage.info("打包中，请稍后……");
    await downloadexamplezip(example, ruleForm.name);
    ElMessage.info("下载完成");
  } else {
    ElMessage.info("没有测试点");
  }
}

async function downloadtip() {
  const zip = new JSZip();
  [1, 2, 3].forEach((v, i) => {
    zip.file(`${i}.in`, "1");
    zip.file(`${i}.out`, "1");
  });
  zip.file(
    "提示.txt",
    "每一个测试点文件需要相同名称的两个文件，这两个文件需要一个为.in为后缀的输入示例、一个为.out为后缀的输出示例"
  );
  zip.generateAsync({ type: "blob" }).then(
    function (blob) {
      const reader = new FileReader();
      reader.readAsDataURL(blob);
      reader.onload = function (e) {
        const a = document.createElement("a");
        a.download = "示例.zip";
        if (e.target) {
          a.href = e.target.result as string;
        } else {
          a.href = location.href;
        }
        a.click();
        a.remove();
      };
    },
    function () {
      ElMessage.error("下载失败");
    }
  );
}

const request: UploadRequestHandler = async (file) => {
  const { size } = file.file;
  if (!prop.isAdmin) {
    if (size > 1024 * 1024 * 1024) {
      ElMessage.error("上传文件过大，最大只能上传1GB");
      return;
    }
  }

  ElNotification({
    title: "解压",
    message: "开始解压",
    type: "info",
  });

  const data = await updatezip(file.file);
  console.log(data)
  ruleForm.testcases = (
    ruleForm.testcases ? ruleForm.testcases : []
  ).concat(data);

  ElNotification({
    title: "解压",
    message: "解压成功",
    type: "success",
  });
  // c("a.zip");
}


// 开始
async function start(_t = false) {
  if (_t) {
    router.push({ query: {} })
    await dealy(50)
  }
  try {
    let data = Question;
    if (Number(prop.ID)) {
      data = await prop.getstart({ ID: Number(prop.ID) });
      Object.assign(ruleForm, data);
    } else {
      Object.assign(ruleForm, data);
    }
    context.value = ruleForm.context || "";
    htmlcontext.value = ruleForm.htmlcontext || "";
    errormessage.value = ruleForm.errormessage || ""
    if (_t) {
      active.value = '0'
    }

  } catch (e: any) {
    ElMessage.error(e);
  }
  dealy(50).then(() => {
    t.value = false
  })
}

/**
 * 添加测试
 */
function addexample(i: boolean, index?: number) {
  if (i) {
    if (ruleForm.testcases && ruleForm.testcases?.length < 50) { // 胖达让改成50
      if (index !== undefined) {
        ruleForm.testcases?.splice(index + 1, 0, {
          input: "",
          output: "",
          isshow: true,
          score: undefined,
          type: 'data'
        });
      } else {
        ruleForm.testcases?.push({
          input: "",
          output: "",
          isshow: true,
          score: undefined,
          type: 'data'
        });
      }
    }
  } else {
    if (index !== undefined) {
      ruleForm.testcases?.splice(index, 1);
    } else {
      ruleForm.testcases?.pop();
    }
  }
}

/**
 * // 提交
 */
async function submit() {
  try {
    console.log('submit')

    if (ruleForm.type === "代码") {
      if (ruleForm.testcases?.length) {
        const n = ruleForm.testcases
          ?.map((e) => e.score)
          .reduce((a = 0, b = 0) => {
            return a + b;
          });
        const score = ruleForm.testcases?.find(e => e.score === undefined || e.score === null)
        if (n !== 100 || score) {
          await ElMessageBox.confirm("测试点分值之和不是100%，是否平均分配测试点得分？", "提示", {
            confirmButtonText: "是",
            cancelButtonText: "否",
            type: "warning",
          }).then(e => {
            settestcasesscore()
          }).catch(e => {
            console.log("测试点分值之和不是100%，取消平均分配测试点得分")
          })
          // return; // 支持测试点分值之和不是100%
        }
      }
    }
    const context = contexteditor.value?.gethtml();
    const htmlcontext = contexteditor.value?.getcontext();
    ruleForm.context = context;
    ruleForm.htmlcontext = htmlcontext;
    ruleForm.errormessage = contexteditor.value?.geterrormessage()
    ruleForm.htmlerrormessage = contexteditor.value?.gethtmlerrormessage()
    ruleForm.user = undefined;
    ruleForm.team = undefined;
    ruleForm.testcases = ruleForm.testcases?.filter(e => {
      return e.input || e.output
    })
    if (!ruleForm.isspecialjudge) {
      ruleForm.specialjudgeid = undefined
    }
    // if (!ruleForm.name && rule.value) {
    //   active.value = '0'
    //   validate(rule.value, { name: [] })
    // }
    if (ruleForm.type === '代码') {

      const n = await prop.asynccreateorupdatequestion(toRaw(ruleForm));
      router.push({
        query: {
          ID: n.ID
        }
      })
      ElMessage({
        message: "添加成功",
        type: "success",
      });
      isdon.value = false;
      active.value = '4'
      successstatus.value = ['success', 'success', 'success', 'success', 'success']
      dealy(50).then(() => {
        t.value = false
      })
      // 提交完成回退

    } else {
      if (ruleForm.type === '排序') {
        if (!ruleForm.answer) {
          ElMessage.error('排序题没有内容')
          return
        }
        ruleForm.answer.answer = Object.keys(ruleForm.answer.options).join('')
      }
      const n = await prop.asynccreateorupdatequestion(toRaw(ruleForm));
      router.push({
        query: {
          ID: n.ID
        }
      })
      ElMessage({
        message: "添加成功",
        type: "success",
      });
      isdon.value = false;
      active.value = '4'
      successstatus.value = ['success', 'success', 'success', 'success', 'success']
      dealy(50).then(() => {
        t.value = false
      })
    }

  } catch (e: any) {
    ElMessage({
      message: e,
      type: "error",
    });
  }
}

// 选择团队
function userhandleCurrentChange(data: Studycodemodel.Iteam) {
  ruleForm.teamid = data.ID;
  ruleForm.team = data;
  dialogVisible2.value = false;
}

// 选择用户
function userhandleCurrentChangeuser(data: Studycodemodel.Iuser) {
  ruleForm.userid = data.ID;
  ruleForm.user = data;
  dialogVisible2.value = false;
}


function updateruleForm(e) {
  console.log(e)
}


const checkbox = computed({
  get() {
    const a = ruleForm.answer?.answer;
    if (!a) {
      return [];
    }
    return String(a).split(",");
  },
  set(v: string[]) {
    if (ruleForm.answer) {
      ruleForm.answer.answer = v.join(",");
    } else {
      ruleForm.answer = {
        answer: v.join(","),
        options: [],
      };
    }
  },
});

function getname(url?: string) {
  const t = url?.split("/");
  if (t) {
    return t[t.length - 1];
  }
  return ''
}

/**
 * 平均生成分数
 */
function settestcasesscore() {
  const length = ruleForm.testcases?.length;
  if (length) {
    const score = Math.floor(100 / length);
    const yu = 100 % length;
    ruleForm.testcases = ruleForm.testcases?.map((e, k) => {
      let n = 0;
      if (k > length - yu - 1) {
        n = n + 1;
      }
      return {
        ...e,
        score: score + n,
      };
    });
  }
}


onBeforeRouteLeave((to, from, next) => {
  if (t.value) {
    const n = window.confirm('你所做的更改可能未保存。')
    if (!n) {
      return
    }
  }
  next()
})

onUnmounted(() => {
  window.onbeforeunload = function () { }
})


</script>

<style scoped>
.demo-ruleForm .demo-ruleForm {
  padding-bottom: 10px;
  min-height: 55vh;
}

.row10 {
  height: 130px;
}

.el-icon-remove {
  cursor: pointer;
}

.width300 {
  width: 100px;
}

.icon {
  margin-right: 6px;
}

.icon-button {
  padding-left: 65px;
  padding-right: 65px;
  font-weight: bold;
  height: 48px;
}

.icon-button a {
  text-decoration: none;
  color: #fff;
}

.icon-class-var path {
  color: var(--el-button-text-color,
      --el-button-hover-color,
      --el-button-active-font-color);
  stroke: var(--el-button-text-color,
      --el-button-hover-color,
      --el-button-active-font-color);
  fill: var(--el-button-text-color,
      --el-button-hover-color,
      --el-button-active-font-color);
}
</style>

<style>
.row10 .row10 textarea {
  height: 130px;
}

.tabs .el-tabs__header {
  display: none;
}

.demo-ruleForm .el-form-item__label {
  color: #8c8c8c !important;
}
</style>